import { Directive, ElementRef, HostListener, ViewContainerRef, OnInit } from '@angular/core';
import { OverlayRef, Overlay } from '@angular/cdk/overlay';
import { Portal, ComponentPortal } from '@angular/cdk/portal';
import { HoverComponent, PeriodicElement } from './hover/hover.component';

@Directive({
  selector: '[appHover]'
})

export class HoverDirective implements OnInit {

  constructor(private el: ElementRef, private overlay: Overlay, private viewContainerRef: ViewContainerRef) { }
  currentPortal: Portal<any>;

  overlayRef: OverlayRef;

  public abc: PeriodicElement;

  @HostListener('mouseenter') onMouseEnter() {
    this.displayMenu();
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.leaveMenu();
  }
  private hover(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }

  ngOnInit() {
    const strategy = this.overlay
      .position()
      .connectedTo(this.el.nativeElement, { originX: 'end', originY: 'bottom' }, { overlayX: 'start', overlayY: 'top' });
    this.overlayRef = this.overlay.create({
      positionStrategy: strategy,
    });
  }

  displayMenu() {
    let portal = new ComponentPortal<HoverComponent>(HoverComponent, this.viewContainerRef);
    let ref = this.overlayRef.attach(portal);
    ref.instance.dataSource = [
      { position: 56, name: 'Lithium', weight: 6.941, symbol: 'Li' },
      { position: 38, name: 'Lithium', weight: 6.941, symbol: 'Li' },
    ]
  }
  leaveMenu() {
    this.overlayRef.detach();
  }
}
